//
//  AudienceLiveViewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/5/2.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import IJKMediaFramework
import SocketIO


class AudienceLiveViewController: LiveViewController {
    
    private lazy var player: IJKFFMoviePlayerController = {
        let options = IJKFFOptions.byDefault()
        let url = URL(string: Network.rtmpHost + room.ruid)
        let player = IJKFFMoviePlayerController(contentURL: url, with: options)!
        player.scalingMode = .aspectFit
        player.shouldAutoplay = true
        return player
    }()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.textAlignment = .center
        label.text = "主播在路上或已下播~"
        label.font = UIFont.systemFont(ofSize: 18)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupPlayer()
        view.insertSubview(tipLabel, at: 0)
        tipLabel.snp.makeConstraints { (make) in
            make.center.left.right.equalToSuperview()
            make.height.equalTo(20)
        }
        dismissBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.leaveAndDisconnet()
            self?.view.endEditing(true)
            self?.safeDismiss()
        })
        .disposed(by: bag)
    }
    
    func setupPlayer(){
        view.insertSubview(player.view, at: 0)
        // 小于 9 : 16， 宽为标准， 大于 9 : 16， 高e为标准
        let width = UIScreen.mainWidth / UIScreen.mainHeight <= 9.0 / 16.0 ? 9.0 / 16.0 * UIScreen.mainHeight : UIScreen.mainWidth
        let height = UIScreen.mainWidth / UIScreen.mainHeight <= 9.0 / 16.0 ? UIScreen.mainHeight : 16.0 / 9.0 * UIScreen.mainWidth
        player.view.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(width)
            make.height.equalTo(height)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.player.prepareToPlay()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.player.shutdown()
    }
}
